package com.example.infrastructure.mapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest requestX = (HttpServletRequest) request;
        HttpServletResponse responseX = (HttpServletResponse) response;
        responseX.setHeader("Access-Control-Allow-Origin", requestX.getHeader("Origin"));
        responseX.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        responseX.setHeader("Access-Control-Max-Age", "3600");
        responseX.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        responseX.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
        // log.info("CORSFilter:{}", requestX.getSession());
        chain.doFilter(request, response);
    }
}
